import React, { useEffect, useState } from 'react'
import style from './AppStyle.module.sass'
import { uploadApi, uploadFinishedApi } from './api';
import SparkMD5 from 'spark-md5'
import useDebounds from './hooks/UesDebounds';
import VirtualList from './components/virtuallist/VirtualList';
import ScrollPage from './components/scroll/ScrollPage';

function App () {

  // #region 变量声明
  const maxLen = 2 * 1024 * 1024
  const spark = new SparkMD5()
  const [value, setValue] = useState('')
  const deValue = useDebounds({value, delay: 1000})
  const list = new Array(1000).fill(false).map((_, index) => `这是滚动内容${index}项`)
  // #endregion

  // #region 函数
  function fileChange (e: React.ChangeEvent<HTMLInputElement>) {
    const files = e.target.files
    if (!files) return
    ;[...files].forEach(async (item) => {
      // 创建读取器
      const fr = new FileReader()
      // 读取为二进制文件
      fr.readAsArrayBuffer(item)
      // 读取完成
      fr.addEventListener('load', (e: Event) => loaded(e, item.name))
    })
  }
  async function loaded (e: Event, fileName: string) {
    // console.log(e.currentTarget?.result as ArrayBuffer)
    const fr = e.currentTarget as FileReader
    const data = fr.result as ArrayBuffer
    // 生成唯一哈希值
    spark.append(data)
    const hashName = spark.end()
    console.log(hashName)
    // 切片
    for (let i = 0; i < data.byteLength; i += maxLen) {
      // 上传
      await uploadApi(data.slice(i, i + maxLen), hashName + '_' + i)
    }
    // 上传结束
    console.log(fileName, hashName)
    // 合并
    const [name, extName] = fileName.split('.')
    uploadFinishedApi(name, extName, hashName)
  }
  // #endregion

  // #region Hooks
  useEffect(() => {
    if (!deValue) return
    console.log(deValue)
  }, [deValue])
  // #endregion

  return (
    <ScrollPage />
  )

  return (
    <div className={style.app}>
      <input type="file" onChange={fileChange} multiple />
      <input type="text" value={value} onChange={(e) => setValue(e.target?.value)} />
      <VirtualList list={list} />
    </div>
  )
}

export default App
